<?php

namespace App\Jobs;

use App\Models\ActivityConfig;
use App\Models\LoginLog;
use App\Models\MediaLikeLog;
use App\Models\MediaLikeStatic;
use App\Models\RegUserStatistics;
use App\Models\User;
use App\Models\UserActive;
use App\Models\RegistrationStatistics;
use App\Models\Shareholder;
use App\Models\MemberShip;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;
use App\Models\InviteSettlementCollect;

class StatisticsQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;

    public function __construct($params)
    {
        $this->params = $params;
    }


    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $parms = $this->params;
        $data = $parms['data'];

        $action = $parms['action'];

        $result = $this->$action($data);

        return $result;
    }

    /*
     *  用户注册统计
     * */
    public function user_add($data)
    {
        $user_total_num = User::count();
        $model = RegUserStatistics::where([['day_date', '=', date("Ymd", time())]])->first();
        if(empty($model)){
            $model = new RegUserStatistics();
            $model->day_date = date("Ymd", time());
            $model->week_date = date('W');
            $model->mon_date = date("Ym", time());
        }
        $model->reg_num = empty($model) ? 1 : ($model->reg_num+1);

        $model->total_user_num = ($user_total_num+1);

        if(!$model->save()){
            $params = [['type' => 'user_add', 'status' => 'error', 'params'=> json_encode($data), 'content' => '增量用户统计异常', 'created_at' => time2date()]];
            insert_mongodb_log('statistics', $params);
            return false;
            // insert_mongodb_log();
        }
        $this->RegistrationStatistics($data);
        return true;
    }

    /*
     * 用户登录统计
     * */
    public function user_login($data)
    {
        try{
            if(empty($data))
                throw new \Exception('未知登录用户');
            if(!isset($data['login_log_id']) && !empty($data['login_log_id']))
                throw new \Exception('未知登陆日志');

            $login_log_id = $data['login_log_id'];
            $login_log_rows = LoginLog::where(['id'=>$login_log_id])->first();
            if(empty($login_log_rows))
                throw new \Exception('未知登陆日志');
            $uid = $login_log_rows->uid;

            $day_key = config('feild.redis.statis.login_statis').':'.date("Ymd", $login_log_rows->create_time).':'.$uid;
            $week_key = config('feild.redis.statis.login_statis').':'.date("W", $login_log_rows->create_time).':'.$uid;
            $mon_key = config('feild.redis.statis.login_statis').':'.date("Ym", $login_log_rows->create_time).':'.$uid;
            $not_active_key = config('feild.redis.statis.login_statis').':'.date("Ymd", $login_log_rows->create_time).':'.$uid;

            $insert_arr = [];
            if(!empty(Redis::get($day_key)))
                return false;
            $key = Redis::setex($day_key, (24*3600), 1);
            Redis::incr($week_key);
            Redis::incr($mon_key);
            Redis::expire($week_key, (7*24*3600));
            Redis::expire($mon_key, (31*24*3600));

            //`type` '类型：1: 日活跃 2：周活跃 3：月活跃 99：不活跃',
            // 日活跃
            $insert_arr[] = ['type' => 1, 'uid' => $uid, 'date_period' => date("Ymd", $login_log_rows->create_time), 'create_time'=>$login_log_rows->create_time];
            // 周
            if(!empty(Redis::get($week_key)) && Redis::get($week_key) >= 5)
                $insert_arr[] = ['type' => 2, 'uid' => $uid, 'date_period' => date("W", $login_log_rows->create_time), 'create_time'=>$login_log_rows->create_time];
            // 月
            if(!empty(Redis::get($mon_key)) && Redis::get($mon_key) >= 15)
                $insert_arr[] = ['type' => 3, 'uid' => $uid, 'date_period' => date("Ym", $login_log_rows->create_time), 'create_time'=>$login_log_rows->create_time];

            if(!empty($insert_arr)){
                foreach ($insert_arr as $key=>$value){
                    $rows = UserActive::where([['type', '=', $value['type']], ['uid', '=', $value['uid']], ['date_period', '=',$value['date_period']]])->first();
                    if(!empty($rows))
                        continue;
                    unset($model);
                    $model = new UserActive();
                    $model->type = $value['type'];
                    $model->uid = $value['uid'];
                    $model->date_period = $value['date_period'];
                    $model->create_time = $value['create_time'];
                    if(!$model->save())
                        throw new \Exception('新增用户活跃数据异常');
                }
            }

            // 统计月不活跃用户
            if(Redis::get($mon_key) == 1){
                unset($insert_arr);
                $insert_arr[] = ['type' => 99, 'uid' => $uid, 'date_period' => date("Ym", $login_log_rows->create_time), 'create_time'=>time()];
                UserActive::insert($insert_arr);
            }

            // 删除月不活跃
            if(Redis::get($mon_key) == 3){
                unset($insert_arr);
                UserActive::where([['type', '=', 99], ['uid', '=', $uid], ['date_period', '=', date("Ym", $login_log_rows->create_time)]])->delete();
            }
        }catch (\Exception $e){
            $params = [['type' => 'user_active', 'status' => 'error', 'params'=> json_encode($data), 'content' => $e->getMessage(), 'created_at' => time2date()]];
            insert_mongodb_log('statistics', $params);
        }
    }
    
    //用户注册统计
    protected function  RegistrationStatistics($data){
        $registered_user_data = User::where(['id'=> $data['uid'],'status'=>1])->first(['parent_id']);
        if(empty($registered_user_data->parent_id)) {
            return true;
        }
        $parent_user_data = User::where(['id'=> $registered_user_data->parent_id,'status'=>1])->first(['mobile']);
        $shareholder_data=  Shareholder::where(['mobile'=>$parent_user_data->mobile ,'status'=>0, 'data_audit' => 1, 'fund_audit' => 1])->first();
        $memberShip_data=  MemberShip::where(['mobile'=>$parent_user_data->mobile ,'status'=>0])->first();
        if($shareholder_data){
           $insert =[
                'uid' =>$data['uid'],
                'reference_id' =>$registered_user_data->parent_id,
                'reference_mobile' => $parent_user_data->mobile,
                'branch_office_id' => $shareholder_data->ascription,
                'type' => 1,
                'created_at' => time2date(),
           ];
        } elseif ($memberShip_data) {
            $insert =[
                'uid' =>$data['uid'],
                'reference_id' =>$registered_user_data->parent_id,
                'reference_mobile' => $parent_user_data->mobile,
                'branch_office_id' => $memberShip_data->ascription,
                'type' => 2,
                'created_at' => time2date(),
            ];
        } else {
            $insert =[
                'uid' =>$data['uid'],
                'reference_id' => $registered_user_data->parent_id ?: 0,
                'reference_mobile' => $parent_user_data->mobile ?: '',
                'branch_office_id' => 0,
                'type' => 3,
                'created_at' => time2date(),
            ];
        }

        RegistrationStatistics::insert($insert);
    }

    /**
     * @desc 创建结算用户记录
     * @param array $data
     * @return bool
     */
    public function add_invite_settlement_user($data)
    {
        $user_info = User::where(['id'=> $data['uid'],'status'=>1])->first(['id','role', 'mobile','membership']);
        $settlement_collect_data = [
            'uid' => $user_info->id,
            'created_at' => time(),
        ];

        if($user_info->role == 1) {
            $ascription_info = Shareholder::where(['data_audit' => 1, 'fund_audit' => 1, 'status' => 0, 'mobile' => $user_info->mobile])->first(['ascription']);
        } elseif($user_info->membership == 1) {
            $ascription_info = MemberShip::where(['status' => 0, 'mobile' => $user_info->mobile])->first(['ascription']);
        }

        if(isset($ascription_info) && !empty($ascription_info)) {
            $settlement_collect_data['ascription'] = $ascription_info->ascription;
        }

        $where_arr = ['uid' => $user_info->id];

        $is_record = InviteSettlementCollect::where($where_arr)->first();
        if(!$is_record) {
            InviteSettlementCollect::insert($settlement_collect_data);
        }

        return true;
    }

    /*
     * 点赞统计
     * */
    public function media_like($data)
    {
        $error = [];
        if(!isset($data['media_like_log_id']))
            return false;

        $type = $data['type'];

        // 校验活动状态
        $activity_config_rows = ActivityConfig::where([['activity_type', '=', 2]])->orderBy('id', 'desc')->first();
        if(empty($activity_config_rows))
            return false;
        if($activity_config_rows->status != 1)
            return false;
        if($activity_config_rows->start_time > time() || $activity_config_rows->end_time < time())
            return false;

        $media_like_log_rows = MediaLikeLog::where([['id', '=', $data['media_like_log_id']]])->first();
        if(!empty($media_like_log_rows)){

            // 统计key：基础+周期+发布者用户+视频id+点赞者 // 每个周期，每个用户对视频点赞key
            $week_redis_key = config('feild.redis.statis.media_like_static.week.key').":".date("W", $media_like_log_rows->create_time).":".$media_like_log_rows->media_id.":".$media_like_log_rows->operation_uid;
            $week_redis_expirce = config('feild.redis.statis.media_like_static.week.exprice_time');
            $month_redis_key = config('feild.redis.statis.media_like_static.month.key').":".date("Ym", $media_like_log_rows->create_time).":".$media_like_log_rows->media_id.":".$media_like_log_rows->operation_uid;
            $month_redis_expirce = config('feild.redis.statis.media_like_static.month.exprice_time');

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 检验周统计    点赞累加
            if(empty(Redis::get($week_redis_key)) && $type == 1){

                $week_static_rows = MediaLikeStatic::where([['type', '=', 1], ['date_format', '=', date("W", $media_like_log_rows->create_time)], ['uid', '=', $media_like_log_rows->media_uid]])->first();
                if(empty($week_static_rows)){
                    $week_static_rows = new MediaLikeStatic();
                    $week_static_rows->type = 1;
                    $week_static_rows->activity_id = $activity_config_rows->id;
                    $week_static_rows->date_format = date("W", $media_like_log_rows->create_time);
                    $week_static_rows->create_time = time();
                    $week_static_rows->uid = $media_like_log_rows->media_uid;
                    $like_num = 1;

                }else{
                    $like_num = $week_static_rows->like_num+1;
                }
                $week_static_rows->update_time = time();
                $week_static_rows->like_num = $like_num;
                // 报错异常
                if(!$week_static_rows->save())
                    $error[] = '点赞统计周数据异常';
                else
                    Redis::setex($week_redis_key, $week_redis_expirce, 1);
            }
            // 取消点赞
            else if(!empty(Redis::get($week_redis_key)) && $type == '-1'){
                $week_static_rows = MediaLikeStatic::where([['type', '=', 1], ['date_format', '=', date("W", $media_like_log_rows->create_time)], ['uid', '=', $media_like_log_rows->media_uid]])->first();
                if(!empty($week_static_rows)){
                    $week_static_rows->like_num = $week_static_rows->like_num-1;
                    if(!$week_static_rows->save())
                        $error[] = '取消点赞统计周数据异常';
                    else
                        Redis::del($week_redis_key);
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 校验月统计
            if(empty(Redis::get($month_redis_key)) && $type == '1'){
                $month_static_rows = MediaLikeStatic::where([['type', '=', 2], ['date_format', '=', date("Ym", $media_like_log_rows->create_time)], ['uid', '=', $media_like_log_rows->media_uid]])->first();
                $month_like_num = 1;
                if(empty($month_static_rows)){
                    $month_static_rows = new MediaLikeStatic();
                    $month_static_rows->type = 2;
                    $week_static_rows->activity_id = $activity_config_rows->id;
                    $month_static_rows->date_format = date("Ym", $media_like_log_rows->create_time);
                    $month_static_rows->create_time = time();
                    $month_static_rows->uid = $media_like_log_rows->media_uid;
                    $month_like_num = 1;
                }else{
                    $month_like_num = $month_static_rows->like_num+1;
                }
                $month_static_rows->update_time = time();
                $month_static_rows->like_num = $month_like_num;

                // 报错异常
                if(!$month_static_rows->save())
                    $error[] = '点赞统计月数据异常';
                else
                    $key = Redis::setex($month_redis_key, $month_redis_expirce, 1);
            }// 取消点赞
            else if(!empty(Redis::get($month_redis_key)) && $type == '-1'){
                $month_static_rows = MediaLikeStatic::where([['type', '=', 2], ['date_format', '=', date("Ym", $media_like_log_rows->create_time)], ['uid', '=', $media_like_log_rows->media_uid]])->first();
                if(!empty($month_static_rows)){
                    $month_static_rows->like_num = $month_static_rows->like_num-1;
                    if(!$month_static_rows->save())
                        $error[] = '取消点赞统计月数据异常';
                    else
                        Redis::del($month_redis_key);
                }
            }
        }

        if(!empty($error)){
            // 监控数据
            $params = [['type' => config('feild.type.monitoring')[1]['id'], 'status' => 'error', 'params' => json_encode($data), 'content' => config('feild.type.monitoring')[1]['title'].implode(',', $error), 'created_at' => time2date()]];
            $result = insert_mongodb_log('ivy_monitoring', $params);
        }
    }

}
